package com.colorlight.cloud.complete.entity.instructions;

import com.colorlight.cloud.common.exception.ParameterException;
import com.colorlight.cloud.common.model.ExceptionEnum;
import com.colorlight.cloud.complete.api.CompleteEntityScheduleActions;
import com.colorlight.cloud.complete.entity.po.SenderVolume;
import com.colorlight.iot.proto.complete.instruction.CompleteInstruction;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 设置发送设备音量
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Slf4j
public class SetSenderVolume implements CompleteEntityScheduleActions {

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public static class InputMsg implements Serializable {
        /**
         * 要设置的发送设备音量
         */
        private List<SenderVolume> volume;
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public static class OutputMsg implements Serializable {
        /**
         * 设置后的发送设备音量
         */
        private List<SenderVolume> volume;
    }

    private InputMsg input;
    private OutputMsg output;

    @Override
    public ByteString objectConvertBytes() {
        final CompleteInstruction.SetSenderVolume.InputMsg.Builder inputMsg =
                CompleteInstruction.SetSenderVolume.InputMsg.newBuilder();
        SetSenderVolume.InputMsg thisInput = this.getInput();
        inputMsg.addAllVolume(thisInput.getVolume().stream().map(SenderVolume::toProto).collect(Collectors.toList()));
        final CompleteInstruction.SetSenderVolume.Builder builder =
                CompleteInstruction.SetSenderVolume.newBuilder();
        builder.setInput(inputMsg);
        return builder.build().toByteString();
    }

    @Override
    public SetSenderVolume byteConvertObject(ByteString bytes) {
        CompleteInstruction.SetSenderVolume setSenderVolume = null;
        try {
            setSenderVolume = CompleteInstruction.SetSenderVolume.parseFrom(bytes);
        } catch (InvalidProtocolBufferException e) {
            log.error("", e);
        }
        if (Objects.isNull(setSenderVolume)) {
            throw new ParameterException(ExceptionEnum.MSG_PARAMETER_EXCEPTION);
        }
        SetSenderVolume.OutputMsg outputMsg = new SetSenderVolume.OutputMsg();
        CompleteInstruction.SetSenderVolume.OutputMsg output = setSenderVolume.getOutput();
        List<SenderVolume> collect = output.getVolumeList().stream()
                .map(p -> new SenderVolume().formProto(p)).collect(Collectors.toList());
        outputMsg.setVolume(collect);
        this.setOutput(outputMsg);
        return this;
    }
}

